package com.gae101;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;
import org.datanucleus.util.StringUtils;

import com.gae101.service.ImageService;
import com.gae101.service.ImageServiceImpl;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class ImageServlet extends HttpServlet {
	private static final long serialVersionUID = 781330892138234604L;
	private static final Logger log = Logger.getLogger(ImageServlet.class.getName());
	
	ImageService imageService = new ImageServiceImpl();
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if (user == null) {
			log.info("uploadimage : not logged user");
			return;
		}
		
		String userId = user.getUserId();

	    try {
	        ServletFileUpload upload = new ServletFileUpload();

	        String location = null;
	        byte[] rawImageData = null;

	        FileItemIterator iterator = upload.getItemIterator(req);
	        while (iterator.hasNext()) {
	          FileItemStream item = iterator.next();
	          InputStream stream = item.openStream();

	          if (item.isFormField()) {
	            log.warning("Got a form field: " + item.getFieldName());
	            if (item.getFieldName().equals("location")) {
	            	location = Streams.asString(stream);
	            }
	          } else {
	        	//log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
	        	if (StringUtils.isEmpty(item.getName())) {
	        		continue;
	        	}

	        	// store image
	            rawImageData = IOUtils.toByteArray(stream);
	            if (rawImageData.length <= 0) {
	            	return;
	            }

	            /*
	            int len;
	            byte[] buffer = new byte[8192];
	            while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
	              res.getOutputStream().write(buffer, 0, len);
	            }
	            */
	          }
	        }
	        
        	if (location.equals("web")) {
        		res.sendRedirect("/");
        	}
        	
        	imageService.save(userId, rawImageData);
	      } catch (Exception ex) {
	        throw new ServletException(ex);
	      }
	    }
}
